const dayjs = require("dayjs")
const { query } = require("../util/dbutil")
const { AssertUtils, IdUtils, RandomUtils } = require("../util/utils")
const sqlWhere = require("../util/SqlWhere");
const sqlUpdate = require("../util/SqlUpdate");
const validation = require("../util/Validation");

function queryIsEmpty(data) {
    const {status, user_id} = data
    AssertUtils.StringNotEmpty(status, "订单状态不能为空")
    AssertUtils.StringNotEmpty(user_id, "用户id不能为空")
}
const getChargePilePayList = async (query) => {
    const arr = ['id','user_id','car_id','%status%']
    const data =  await new sqlWhere(`select 
    id,
    status,
    charged_quantity,
    money,
    cs_id,
    pay_type,
    user_id,
    diff_money,
    amount,
    car_id,
    DATE_FORMAT(start_time, '%Y-%m-%d %H:%i:%s') as start_time,
    DATE_FORMAT(end_time, '%Y-%m-%d %H:%i:%s') as end_time,
    DATE_FORMAT(pay_time, '%Y-%m-%d %H:%i:%s') as pay_time,
    DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') as create_time
from orders`, query)
        .addQueryCriteriaMultiple(arr)
        .setPagination()
        .executeTheQuery()
    const result = await new sqlWhere('SELECT COUNT(*) AS count FROM orders',query)
        .addQueryCriteriaMultiple(arr)
        .executeTheQuery()
    return {
        data,
        result
    }
}

const addChargePilePay = async (data) => {
    queryIsEmpty(data)
    const keyArr = Object.keys(data)
    const valArr = Object.values(data)
    const arr = Object.keys(data).fill('?').join()
    return await query(`insert into orders (${keyArr.join()}) values (${arr})`,valArr)
}
const updateChargePilePay = async (data) => {
    AssertUtils.StringNotEmpty(data.id, "订单编号不能为空")
    return await new sqlUpdate(`update orders set`,data)
        .setSearchCriteria(Object.keys(data))
        .setQueryCriteria(`where id=${data.id}`)
        .execUpdate()
}

const deleteChargePilePay = async (id) => {
    AssertUtils.StringNotEmpty(id, "订单编号不能为空")
    return await query(`DELETE FROM orders WHERE id = ?`,[id])
}


module.exports = {
    addChargePilePay,
    updateChargePilePay,
    deleteChargePilePay,
    getChargePilePayList
}
